from rw.www import WebSocketHandler

from fullsteam import json


class SteamSocket(WebSocketHandler):
    def on_message(self, message):
        try:
            obj = json.loads(message)
        except:
            print 'sorry, you send something that is NOT JSON'
            print message
            obj = None

        if obj:
            self.on_json(obj)

    def write_message(self, message):
        message = json.to_jsonable(message)
        try:
            WebSocketHandler.write_message(self, json.dumps(message))
        except AttributeError:
            print 'connection seems dead'
            self.on_close()

    def call(self, function_name, *args):
        print 'call function:', function_name, repr(args)
        self.write_message({'method': function_name, 'arguments': args})
